package com.up.stores.controller;

import com.up.stores.controller.ex.*;
import com.up.stores.entity.Admin;
import com.up.stores.entity.Bussinessman;
import com.up.stores.entity.User;
import com.up.stores.service.IBaseAdminService;
import com.up.stores.service.IBaseBussService;
import com.up.stores.service.IBaseUserService;
import com.up.stores.until.JsonResult;
import com.up.stores.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 主要实现学生的创建、信息完善、发起关联
 */
@Api(tags="用户模块")
@RestController
@RequestMapping("/user")
public class UserInfoController extends BaseController {

    @Autowired
    private IBaseUserService BaseUserService;
    @Autowired
    private IBaseAdminService BaseAdminService;
    @Autowired
    private IBaseBussService BaseBussService;
    /**
     * 注册事件
     */
    @ApiOperation(value="注册")
    @PostMapping("/reg")
    public JsonResult<Void> reg(String realName, String username, String password, String password2, String phone, String email, String Type){
        if(Type.equals("User")){
            BaseUserService.reg(realName, username, password, password2, phone, email);
        }else if(Type.equals("Buss")){
            BaseBussService.reg(realName, username, password, password2, phone, email);
        }else if(Type.equals("Admin")){
            BaseAdminService.reg(realName, username, password, password2, phone, email);
        }
        return new JsonResult<Void>(OK);
    }

    /**
     * 登入
     * 三合一
     */
    @ApiOperation(value="登录")
    @PostMapping("/login")
    public JsonResult<Void> login(String name,
                                  String password,
                                  HttpSession session,
                                  String Type){
        session.setMaxInactiveInterval(-1);
        String parent = session.getServletContext().getRealPath("upload");
        session.setAttribute("path", parent);
        if(Type.equals("User")){
            User data=BaseUserService.login(name,password);
            session.setAttribute("uid",data.getNorId());
            session.setAttribute("username",data.getUserName());
            session.setAttribute("type","User");
        }
        else if(Type.equals("Admin")){
            Admin data=BaseAdminService.login(name,password);
            session.setAttribute("uid",data.getAdmId());
            session.setAttribute("username",data.getAdminName());
            session.setAttribute("type","Admin");
        }
        else if(Type.equals("Buss")){
            Bussinessman data=BaseBussService.login(name,password);
            session.setAttribute("uid",data.getBusId());
            session.setAttribute("username",data.getBusName());
            session.setAttribute("type","Buss");
        }
        //获取session中绑定的数据
        System.out.println("uid:"+getuidFromSession(session));
        System.out.println("用户"+getUsernameFromSession(session)+"登录成功！");
        return new JsonResult<Void>(OK);

    }

    /**
     * 更新密码
     *
     */
    @ApiOperation(value="修改密码")
    @PutMapping("/change_password")
    public JsonResult<Void> changePassword(String oldPassword,
                                           String newPassword,
                                           String newPassword2,
                                           HttpSession session){
        Integer uid = getuidFromSession(session);
        String username=getUsernameFromSession(session);
        String type = getTypeFromSession(session);
        if(type.equals("Admin")){
            BaseAdminService.changePassword(uid, username, oldPassword, newPassword, newPassword2);
        }else if(type.equals("User")){
            BaseUserService.changePassword(uid, username, oldPassword, newPassword, newPassword2);
        }else if(type.equals("Buss")){
            BaseBussService.changePassword(uid, username, oldPassword, newPassword, newPassword2);
        }
        return new JsonResult<Void>(OK);
    }

    /**
     * 查询信息（通过session中的uid）
     */
    @ApiOperation(value="获取当前普通用户信息")
    @GetMapping("nor/get_by_id")
    public JsonResult<UserVO> getByNorId(HttpSession session){
        Integer uid = getuidFromSession(session);
        UserVO result = BaseUserService.getByUid(uid);
        return new JsonResult<UserVO>(OK,result);
    }

    @ApiOperation(value="获取当前商家信息")
    @GetMapping("bus/get_by_id")
    public JsonResult<Bussinessman> getByBusId(HttpSession session){
        Integer uid = getuidFromSession(session);
        Bussinessman result = BaseBussService.getByUid(uid);
        return new JsonResult<Bussinessman>(OK,result);
    }

    @ApiOperation(value="获取当前管理员信息")
    @GetMapping("adm/get_by_id")
    public JsonResult<Admin> getByAdmId(HttpSession session){
        Integer uid = getuidFromSession(session);
        Admin result = BaseAdminService.getByUid(uid);
        return new JsonResult<Admin>(OK,result);
    }



    /**
     * 完善资料
     * 包含图片处理
     * 上传图像，用户商家二合一
     */
    /** 头像文件大小的上限值(10MB) */
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    /** 允许上传的头像的文件类型 */
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();
    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
    }

    @ApiOperation(value="修改头像")
    @PostMapping("/change_avatar")
    public JsonResult<Void> changeAvater(HttpSession session,
                                          MultipartFile file) throws FileUploadIOException {

        String Type=getTypeFromSession(session);
        // 判断上传的文件是否为空
        if (file.isEmpty()) {
            // 是：抛出异常
            throw new FileEmptyException("上传的头像文件不允许为空");
        }

        // 判断上传的文件大小是否超出限制值
        if (file.getSize() > AVATAR_MAX_SIZE) { // getSize()：返回文件的大小，以字节为单位
            // 是：抛出异常
            throw new FileSizeException("不允许上传超过" + (AVATAR_MAX_SIZE / 1024) + "KB的头像文件");
        }

        // 判断上传的文件类型是否超出限制
        String contentType = file.getContentType();
        // public boolean list.contains(Object o)：当前列表若包含某元素，返回结果为true；若不包含该元素，返回结果为false。
        if (!AVATAR_TYPES.contains(contentType)) {
            // 是：抛出异常
            throw new FileTypeException("不支持使用该类型的文件作为头像，允许的文件类型：\n" + AVATAR_TYPES);
        }

        /**
         * session.getServletContext()获取当前Web应用程序的上下文
         * 对象(每次启动tomcat都会创建一个新的上下文对象)
         * getRealPath("/upload")的/代表当前web应用程序的根目录,通过该相
         * 对路径获取绝对路径,返回一个路径字符串,如果不能进行映射返回null,单
         * 斜杠可要可不要
         */

        // 获取当前项目的绝对磁盘路径
        //String parent = session.getServletContext().getRealPath("upload");
        //System.out.println("这是根目录"+getRealPathFromSession(session));
        String parent = "/root/Pictures";
        // 保存头像文件的文件夹
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存的头像文件的文件名
        String suffix = "";
        String originalFilename = file.getOriginalFilename();
        int beginIndex = originalFilename.lastIndexOf(".");
        if (beginIndex > 0) {
            suffix = originalFilename.substring(beginIndex);
        }
        String filename =
        UUID.randomUUID().toString() + suffix;
        // 创建文件对象，表示保存的头像文件
        File dest = new File(dir, filename);
        // 执行保存头像文件
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            // 抛出异常
            throw new FileStateException("文件状态异常，可能文件已被移动或删除");
        } catch (IOException e) {
            // 抛出异常
            throw new FileUploadIOException("上传文件时读写错误，请稍后重尝试");
        }
        // 头像路径
        String avatar = "http://101.34.3.160:8080" + parent + "/" + filename;

        if(Type.equals("User")){
            BaseUserService.changeAvatar(getuidFromSession(session),getUsernameFromSession(session),avatar);
        }
        else if(Type.equals("Buss")){
            BaseBussService.changeAvatar(getuidFromSession(session),getUsernameFromSession(session),avatar);
        }
        else if(Type.equals("Admin")){
            BaseAdminService.changeAvatar(getuidFromSession(session),getUsernameFromSession(session),avatar);
        }
        return new JsonResult<Void>(OK);
    }

    /**
     * 完善信息
     * 传入的信息不一样，不能二合一
     */
    //普通用户
    @ApiOperation(value="普通用户更新信息")
    @PutMapping("nor/updateInfo")
    public JsonResult<Void> NorUpdateInfo(HttpSession session,
                                           User user){
        BaseUserService.changeInfo(user,getuidFromSession(session));
        return new JsonResult<Void>(OK);
    }

    //商家
    @ApiOperation(value="商家更新信息")
    @PutMapping("bus/updateInfo")
    public JsonResult<Void> BusUpdateInfo(HttpSession session,
                                         Bussinessman bus){
        BaseBussService.changeInfo(bus,getuidFromSession(session));
        return new JsonResult<Void>(OK);
    }

    //管理员
    @ApiOperation(value="管理员更新信息")
    @PutMapping("adm/updateInfo")
    public JsonResult<Void> AdmUpdateInfo(HttpSession session,
                                         Admin admin){
        BaseAdminService.changeInfo(admin,getuidFromSession(session));
        return new JsonResult<Void>(OK);
    }

    //退出登录
    @ApiOperation(value="退出登录")
    @GetMapping("quit")
    public JsonResult<Void> Quit(HttpSession session) {
        String username = getUsernameFromSession(session);
        session.invalidate();
        System.out.println(username+"退出登录");
        return new JsonResult<Void>(OK);
    }

    @ApiOperation(value="test")
    @PostMapping("test")
    public JsonResult<Void> test(@RequestBody HashMap<Integer, Integer> hashMap) {
        System.out.println(hashMap);
        System.out.println(hashMap.get(1));
        return new JsonResult<Void>(OK);
    }
}
